import ContentContainer from "../components/ContentContainer";
import { Card, Stack, Typography } from "@mui/material";
import { withBase } from "../utils/ui";
import authService from "../service/authService";
import { useEffect, useState, useRef } from "react";


const MePage = () => {
  const [user, setUser] = useState(authService.getUser());

  useEffect(() => {
    let intervalId;

    if (!user) {
      intervalId = setInterval(async () => {
        try {
          const wxUser = await authService.getWxUser();
          if (!wxUser) {
            return;
          }
          authService.setUser(wxUser);
          setUser(wxUser); // 更新组件状态
          clearInterval(intervalId); // 获取到用户后停止轮询
        } catch (error) {
          console.error('获取微信用户失败:', error);
        }
      }, 1000); // 每秒轮询一次
    }
    console.log('get user:', user);
    // 清理函数，组件卸载或 user 改变时清除 interval
    return () => clearInterval(intervalId);
  }, [user]);

  return (
    <ContentContainer>
      <Stack spacing={2}>
        {user && 
          <Card className="shadow-md" variant="outlined" sx={{textAlign: "center", padding: "20px"}}>
            <Typography variant="h6">欢迎你，{user?.username}</Typography>
          </Card>
        }
        {!user && 
          <Card className="shadow-md" variant="outlined" sx={{textAlign: "center", padding: "20px"}}>
            <Typography variant="h5">扫码登录</Typography>
            <img src={withBase("/images/jsb-bar-code.png")} alt="Profile" />
            <Typography variant="h6">关注公众号，发送暗号: 666</Typography>
          </Card>
        }
      </Stack>
    </ContentContainer>
  );
}

export default MePage;